package com.ezjie.ielts.module_word;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.model.FilterWordData;
import com.ezjie.ielts.model.FilterWordResponse;
import com.ezjie.ielts.model.WordHomeData;
import com.ezjie.ielts.model.WordHomeResponse;
import com.ezjie.ielts.model.WordNewCheckData;
import com.ezjie.ielts.model.WordNewCheckResponse;
import com.ezjie.ielts.model.WordStudyingData;
import com.ezjie.ielts.model.WordStudyingResponse;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DateUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.ezjie.ielts.view.WordHomeRoundProgressBar;
import com.ezjie.ielts.widget.CustomDialog;
import com.ezjie.ielts.widget.TitleTextView;
import com.ezjie.login.LoginActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

/**
 * 词汇练习界面
 * 
 * @author renyangyang
 *
 */
@ContentView(R.layout.layout_word_practice)
public class WordPracticeActivity extends BaseFragmentActivity {
	private static final String TAG = WordPracticeActivity.class.getSimpleName();

	private Context mContext;

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.iv_topbar_right)
	private ImageView iv_topbar_right;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	@ViewInject(R.id.rl_new_word)
	private RelativeLayout rl_new_word;// 新学词汇
	@ViewInject(R.id.rl_review)
	private RelativeLayout rl_review;// 复习计划
	@ViewInject(R.id.tv_studyTip)
	private TextView tv_studyTip;
	@ViewInject(R.id.tv_reviewTip)
	private TextView tv_reviewTip;// 复习的提示
	@ViewInject(R.id.tv_reviewProgress)
	private TextView tv_reviewProgress;// 复习的状态
	@ViewInject(R.id.tv_studyProgress)
	private TextView tv_studyProgress;
	@ViewInject(R.id.tv_studyingProgress)
	private TextView tv_studyingProgress;
	@ViewInject(R.id.tv_studyingNum)
	private TextView tv_studyingNum;
	@ViewInject(R.id.tv_totalNum)
	private TextView tv_totalNum;
	@ViewInject(R.id.tv_finishDay)
	private TextView tv_finishDay;
	@ViewInject(R.id.iv_wenhao)
	private ImageView iv_wenhao;// 问号
	@ViewInject(R.id.iv_unclick)
	private ImageView iv_unclick;// 不可点击
	@ViewInject(R.id.rpb_getWord)
	private WordHomeRoundProgressBar rpb_getWord;

	private WordHomeData wordHomeData;
	private WordDao wordDao;
	private boolean isFirstResume;// 是第一次显示onResume 还是从其他界面回来显示的onResume

	private WordTask mWordTask;
	private UserInfoDB userInfoDB;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ViewUtils.inject(this);
		mContext = this;
		wordDao = new WordDao(this);
		isFirstResume = true;
		mWordTask = new WordTask(this);
		userInfoDB = new UserInfoDB(this);

		init();

	}

	private void init() {
		iv_topbar_back.setOnClickListener(this);
		tv_topbar_title.setText(R.string.word_practice_title);

		iv_topbar_right.setVisibility(View.VISIBLE);
		iv_topbar_right.setImageResource(R.drawable.word_agenda_btn);

		iv_topbar_right.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 日历
				if (this != null) {
					Intent intent = new Intent(mContext, WordAgendaActivity.class);
					startActivity(intent);
				}
			}
		});

		rl_new_word.setOnClickListener(this);
		rl_review.setOnClickListener(this);
		iv_wenhao.setOnClickListener(this);

		// 判断sharedPre中是否有当天的数据，如果有，就显示数据
		if (WordHomeDataUtil.isTodayData(this)) {
			wordHomeData = WordHomeDataUtil.getWordHomeData(this);
			initAllView(false);
		}

		getWordHome();
		// 请求是否有单词更新
		getWordIsUpdate();

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_PRACTICE);
		
		if (isFirstResume) {
			isFirstResume = false;
		} else {
			if (WordHomeDataUtil.isTodayData(this)) {
				// 1.根据触发条件 取出sharePre中的值 加入到wordHomeData中
				int todayStudied = WordHomeDataUtil.getTodayStudied(this);
				int todayStudying = WordHomeDataUtil.getTodayStudying(this);
				int reviewNum = WordHomeDataUtil.getReviewNum(this);
				int reviewedNum = WordHomeDataUtil.getReviewedNum(this);
				int wordStudingNum = WordHomeDataUtil.getWordStudingNum(this);
				int wordMasterNum = WordHomeDataUtil.getWordMasterNum(this);
				if (wordHomeData != null) {
					if (todayStudying != -1) {
						wordHomeData.today_studying = todayStudying;
					}
					wordHomeData.today_studied = wordHomeData.today_studied + todayStudied;

					if (reviewNum > 0) {
						wordHomeData.review = wordHomeData.review + reviewNum;
					}
					if (reviewedNum > 0) {
						wordHomeData.reviewed = wordHomeData.reviewed + reviewedNum;
					}
					if (wordStudingNum != 0) {
						wordHomeData.studying = wordHomeData.studying + wordStudingNum;
					}
					if (wordMasterNum > 0) {
						wordHomeData.complete = wordHomeData.complete + wordMasterNum;
					}
				}

				WordHomeDataUtil.putTodayStudied0(this);
				WordHomeDataUtil.putReviewNum0(this);
				WordHomeDataUtil.putReviewedNum0(this);
				WordHomeDataUtil.putWordStudyingNum0(this);
				WordHomeDataUtil.putWordMasterNum0(this);

				if (wordHomeData == null) {
					wordHomeData = WordHomeDataUtil.getWordHomeData(this);
				}
				// 2.显示allView
				initAllView(true);
			} else {
				// 今日数据已无效，需要重新请求数据 界面上的数据也要恢复 初始值
				if (wordHomeData != null) {
					wordHomeData.review = 0;
					wordHomeData.today_studied = 0;
					wordHomeData.today_studying = 0;
				}
				WordHomeDataUtil.putTodayStudied0(this);
				WordHomeDataUtil.putReviewNum0(this);
				WordHomeDataUtil.putReviewedNum0(this);
				WordHomeDataUtil.putTodayStudying_1(this);
				WordHomeDataUtil.putWordStudyingNum0(this);
				WordHomeDataUtil.putWordMasterNum0(this);

				initAllView(false);
				getWordHome();
			}
		}

	}

	private void getWordIsUpdate() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		mWordTask.getWordIsUpdate(WordHomeDataUtil.getWordUpdateTime(this), "check", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordNewCheckResponse wordNewCheckResponse = JSON.parseObject(result, WordNewCheckResponse.class);
					if (wordNewCheckResponse != null && 200 == wordNewCheckResponse.getStatus_code()) {
						WordNewCheckData data = wordNewCheckResponse.getData();
						if (data != null) {
							int state = data.getState();
							if (state == 1) {
								// 有更新了
								WordHomeDataUtil.putWordHaveUpdate(mContext, true);
								// 显示对话框
								showWordUpdateDialog();
							} else {
								WordHomeDataUtil.putWordHaveUpdate(mContext, false);
							}
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});

	}

	@Override
	public void onPause() {
		super.onPause();
		
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_PRACTICE);
		
		WordHomeDataUtil.putWordHomeData(this, wordHomeData);
	}

	@Override
	public void onBackPressed() {
		WordHomeDataUtil.putWordHomeData(this, wordHomeData);
		finish();
	}

	private void showWordUpdateDialog() {
		// 有单词更新
		// 有复习计划未完成
		View view = LayoutInflater.from(this).inflate(R.layout.layout_rob_warn_dialog, null);

		final Dialog dialog = new Dialog(this, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_content.setText(R.string.word_practice_have_update);
		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		ll_layout1.setVisibility(View.VISIBLE);
		ll_layout2.setVisibility(View.GONE);

		Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
		Button btn_no = (Button) view.findViewById(R.id.btn_no);
		btn_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
					// 离线管理
					Intent intent = new Intent(mContext, OfflineManageActivity.class);
					startActivity(intent);
				}

			}
		});

	}

	private void showHintDialog() {
		// 有复习计划未完成

		final CustomDialog dialog = new CustomDialog(mContext, R.layout.layout_word_wenhao_dialog, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();

		Button btn_yes = (Button) dialog.findViewById(R.id.btn_yes);
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
	}

	private void judgeFinishDialog() {
		// 有复习计划未完成
		View view = LayoutInflater.from(mContext).inflate(R.layout.layout_rob_warn_dialog, null);

		final Dialog dialog = new Dialog(mContext, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_content.setText(R.string.word_new_study_warn_msg);
		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		ll_layout1.setVisibility(View.VISIBLE);
		ll_layout2.setVisibility(View.GONE);

		Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
		Button btn_no = (Button) view.findViewById(R.id.btn_no);
		btn_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				// 要判断是否有学习中得
				judgeWordIntent();
			}
		});

	}

	/**
	 * 获取 词汇首页数据
	 */
	private void getWordHome() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}

		mWordTask.getWordHome(DateUtil.getLocalTimeZone(), new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordHomeResponse wordHomeResponse = JSON.parseObject(result, WordHomeResponse.class);
					if (wordHomeResponse != null && 200 == wordHomeResponse.getStatus_code()) {
						String data = wordHomeResponse.getData();
						if (!TextUtils.isEmpty(data)) {
							if (this != null) {
								WordHomeDataUtil.putWordSaveDate(mContext);
							}
							wordHomeData = JSON.parseObject(data, WordHomeData.class);
							// 重新请求数据了，要把 sharePre中数据清空
							WordHomeDataUtil.putTodayStudied0(mContext);
							WordHomeDataUtil.putReviewNum0(mContext);
							WordHomeDataUtil.putReviewedNum0(mContext);
							WordHomeDataUtil.putTodayStudying_1(mContext);
							WordHomeDataUtil.putWordStudyingNum0(mContext);
							WordHomeDataUtil.putWordMasterNum0(mContext);

							WordHomeDataUtil.putWordDaysFuture(mContext, -1);
							initAllView(true);
						}

					} else {
						AppUtil.showToast(mContext, R.string.load_net_data_failure);
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});

	}

	/**
	 * 判断跳转，根据 today_studying判断跳转到筛词，还是第一次学习界面
	 */
	private void judgeWordIntent() {
		if (wordHomeData != null) {
			// wordHomeData.setToday_studying(1);

			int today_studying = wordHomeData.today_studying;
			if (today_studying > 0) {
				// 正在学习的单词组
				getStudyingWord();
			} else if (today_studying == 0) {
				getShaiciWord();
			}
		}
	}

	/**
	 * 获取筛词数据
	 */
	private void getShaiciWord() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}

		mWordTask.getShaiciWord("simple", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					FilterWordResponse filterWordResponse = JSON.parseObject(result, FilterWordResponse.class);
					if (filterWordResponse != null && 200 == filterWordResponse.getStatus_code()) {
						String data = filterWordResponse.getData();
						if (!TextUtils.isEmpty(data)) {
							FilterWordData filterWordData = JSON.parseObject(data, FilterWordData.class);

							YsApplication myApplication = (YsApplication) getApplication();
							myApplication.setFilterWordData(filterWordData);

							startActivity(new Intent(mContext, WordFilterActivity.class));
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});

	}

	private void getStudyingWord() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}

		mWordTask.getStudyingWord("simple", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordStudyingResponse wordStudyingResponse = JSON.parseObject(result, WordStudyingResponse.class);
					if (wordStudyingResponse != null && 200 == wordStudyingResponse.getStatus_code()) {
						String data = wordStudyingResponse.getData();

						if (!TextUtils.isEmpty(data)) {
							WordStudyingData wordStudyingData = JSON.parseObject(data, WordStudyingData.class);
							YsApplication myApplication = (YsApplication) getApplication();
							myApplication.setWordStudyingData(wordStudyingData);
							startActivity(new Intent(mContext, WordStudyManagerActivity.class));// fragment_word_first_study

						}

					} else {
						if (this != null) {
							AppUtil.showToast(mContext, R.string.load_net_data_failure);
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});

	}

	private void initAllView(boolean isAnimation) {
		if (wordHomeData != null) {

			tv_studyTip.setText(wordHomeData.study_hint);
			tv_reviewTip.setText(wordHomeData.review_hint);

			// 复习
			if (wordHomeData.review == 0) {
				// 暂无待复习内容
				tv_reviewProgress.setText(R.string.word_practice_no_review);
				iv_unclick.setVisibility(View.VISIBLE);
				// rl_review.setBackgroundResource(R.drawable.word_hui);
			} else {
				iv_unclick.setVisibility(View.GONE);
				// rl_review.setBackgroundResource(R.drawable.word_huang);
				int review = wordHomeData.review;// 复习总数
				int reviewed = wordHomeData.reviewed;// 已复习
				if (reviewed > review) {
					reviewed = review;
				}
				tv_reviewProgress
						.setText(String.format(getResources().getString(R.string.word_practice_review_progress_str), ""
								+ (review - reviewed)));
			}
			// 学习
			int today_studied = wordHomeData.today_studied;
			// 今日已学习
			int today_studying = wordHomeData.today_studying;
			if (today_studied == 0) {
				tv_studyProgress.setText("");
			} else {
				tv_studyProgress.setText(String.format(
						getResources().getString(R.string.word_practice_study_progress_str), "" + today_studied));
			}
			// 今日学习中
			if (today_studying == 0) {
				tv_studyingProgress.setText("");
			} else {
				tv_studyingProgress.setText(String.format(
						getResources().getString(R.string.word_practice_studying_progress_str), "" + today_studying));
			}

			int complete = wordHomeData.complete;
			int studying = wordHomeData.studying;
			int total = wordHomeData.total;
			if (complete + studying >= total) {
				// 已筛选完
				tv_studyProgress.setText(R.string.word_practice_finish_new);
			}
			if (complete >= total) {
				// 已复习完
				tv_reviewProgress.setText(R.string.word_practice_finish_review);
			}

			tv_studyingNum.setText(wordHomeData.studying + "");
			tv_totalNum.setText(wordHomeData.total + "");
			int days_future = wordHomeData.days_future;
			int wordDaysFuture = WordHomeDataUtil.getWordDaysFuture(this);
			// 哪个小，显示哪个

			if (wordDaysFuture > 0) {
				tv_finishDay.setText(wordDaysFuture + "");
			} else {
				if (days_future < 0) {
					tv_finishDay.setText("--");
				} else {
					tv_finishDay.setText(days_future + "");
				}
			}

			// 最下面圆圈
			rpb_getWord.setMax(total);
			if (isAnimation) {
				rpb_getWord.setAnimationProgress(complete);
			} else {
				rpb_getWord.setProgress(complete);
			}
		}
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			onBackPressed();
			break;
		case R.id.rl_new_word:
			//友盟统计
			MobclickAgent.onEvent(mContext, "word_learn_new_wordBtn");
			if (userInfoDB.queryLoginUser().islogin == 0) {
				startActivity(new Intent(mContext, LoginActivity.class));
				return;
			}
			// 判断是否有复习计划尚未完成
			if (wordHomeData != null) {
				/*
				 * int review = wordHomeData.getReview(); int reviewed =
				 * wordHomeData.getReviewed(); if (reviewed < review) {
				 * judgeFinishDialog(); } else { judgeWordIntent(); }
				 */
				int total = wordHomeData.total;
				int complete = wordHomeData.complete;
				int studying = wordHomeData.studying;
				// total是本地数据库单词的数量 is_active=1的
				if (wordDao != null) {
					total = wordDao.queryCountByIsActive();
					LogUtils.d("本地单词的数量：" + total);
				}
				if (studying + complete >= total) {
					// 您已学完所有的单词，请继续完成复习计划
					AppUtil.showToast(mContext, R.string.word_practice_new_finish_click);
					return;
				}
				judgeWordIntent();
			}
			break;
		case R.id.rl_review:
			// 友盟统计
			MobclickAgent.onEvent(this, "word_review_solidifyBtn");
			if (userInfoDB.queryLoginUser().islogin == 0) {
				startActivity(new Intent(mContext, LoginActivity.class));
				return;
			}
			if (wordHomeData != null) {
				int total = wordHomeData.total;
				int complete = wordHomeData.complete;
				if (complete >= total) {
					// 您已掌握所有的单词，请前往其它栏目进行练习
					AppUtil.showToast(mContext, R.string.word_practice_review_finish_click);
					return;
				}
			}
			if (iv_unclick.getVisibility() == View.VISIBLE) {
				AppUtil.showToast(mContext, R.string.word_practice_un_click_hint);
			} else {
				// 复习
				if (wordHomeData != null) {

					Intent errorIntent = new Intent(mContext, ReviewDetailActivity.class);
					errorIntent.putExtra("type", 0);
					startActivity(errorIntent);
				}

			}

			break;
		case R.id.iv_wenhao:
			// 友盟统计
			MobclickAgent.onEvent(this, "word_learning_point");
			// 问号
			showHintDialog();

			break;
		default:
			break;
		}
	}
}
